<template>
  <div class="role-management">
    <div class="page-header">
      <h1 class="page-title">角色管理</h1>
      <p class="page-description">管理系统角色，配置角色权限，为管理员分配角色</p>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button type="primary" @click="handleAddRole">
          <el-icon>
            <Plus />
          </el-icon>
          添加角色
        </el-button>
        <el-button @click="handleRefresh">
          <el-icon>
            <Refresh />
          </el-icon>
          刷新
        </el-button>
      </div>
      <div class="action-right">
        <el-input v-model="searchKeyword" placeholder="搜索角色名称、描述..." :prefix-icon="Search" clearable
          style="width: 300px;" />
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table :data="filteredTableData" style="width: 100%" v-loading="loading" row-key="id" stripe border>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色代码" width="150" />
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column prop="permissionCount" label="权限数量" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ row.permissions?.length || 0 }} 个</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userCount" label="用户数量" width="120">
          <template #default="{ row }">
            <el-tag type="success">{{ row.userCount || 0 }} 人</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEditRole(row)">编辑</el-button>
            <el-button size="small" type="primary" @click="handleAssignPermissions(row)">
              权限配置
            </el-button>
            <el-button size="small" type="warning" @click="handleAssignUsers(row)">
              用户分配
            </el-button>
            <el-button size="small" type="danger" @click="handleDeleteRole(row)" :disabled="row.code === 'super_admin'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.current" v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 角色表单抽屉 -->
    <RoleFormDrawer v-model:visible="roleDrawerVisible" :role-data="currentRole" :is-edit="isEditMode"
      @submit="handleRoleFormSubmit" />

    <!-- 权限分配抽屉 -->
    <PermissionAssignDrawer v-model:visible="permissionDrawerVisible" :role-data="currentRole"
      @submit="handlePermissionAssign" />

    <!-- 用户分配抽屉 -->
    <UserAssignDrawer v-model:visible="userDrawerVisible" :role-data="currentRole" @submit="handleUserAssign" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Refresh, Search } from '@element-plus/icons-vue'
import RoleFormDrawer from '@/components/AdminInfo/RoleFormDrawer.vue'
import PermissionAssignDrawer from '@/components/AdminInfo/PermissionAssignDrawer.vue'
import UserAssignDrawer from '@/components/AdminInfo/UserAssignDrawer.vue'

// 响应式数据
const loading = ref(false)
const searchKeyword = ref('')
const tableData = ref([])
const pagination = ref({
  current: 1,
  pageSize: 20,
  total: 0
})

// 抽屉相关状态
const roleDrawerVisible = ref(false)
const permissionDrawerVisible = ref(false)
const userDrawerVisible = ref(false)
const isEditMode = ref(false)
const currentRole = ref({})

// 模拟角色数据
const mockRoleData = [
  {
    id: 1,
    name: '超级管理员',
    code: 'super_admin',
    description: '拥有系统所有权限的超级管理员',
    permissions: ['user:view', 'user:edit', 'user:delete', 'content:view', 'content:edit', 'content:delete', 'system:view', 'system:edit', 'system:config', 'role:view', 'role:edit', 'role:delete'],
    userCount: 1,
    status: '启用',
    createTime: '2023-12-01 09:00:00'
  },
  {
    id: 2,
    name: '系统管理员',
    code: 'system_admin',
    description: '负责系统日常维护和用户管理',
    permissions: ['user:view', 'user:edit', 'content:view', 'content:edit', 'system:view', 'role:view'],
    userCount: 3,
    status: '启用',
    createTime: '2023-11-20 10:30:00'
  },
  {
    id: 3,
    name: '内容管理员',
    code: 'content_admin',
    description: '负责内容审核和发布管理',
    permissions: ['content:view', 'content:edit', 'content:audit'],
    userCount: 5,
    status: '启用',
    createTime: '2023-10-15 14:15:00'
  },
  {
    id: 4,
    name: '审核员',
    code: 'auditor',
    description: '负责内容审核工作',
    permissions: ['content:view', 'content:audit'],
    userCount: 2,
    status: '禁用',
    createTime: '2023-09-01 16:20:00'
  }
]

// 计算属性
const filteredTableData = computed(() => {
  if (!searchKeyword.value) return tableData.value

  return tableData.value.filter(item =>
    item.name.includes(searchKeyword.value) ||
    item.description.includes(searchKeyword.value) ||
    item.code.includes(searchKeyword.value)
  )
})

// 方法
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 800))
    tableData.value = mockRoleData
    pagination.value.total = mockRoleData.length
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const handleAddRole = () => {
  isEditMode.value = false
  currentRole.value = {}
  roleDrawerVisible.value = true
}

const handleEditRole = (row) => {
  isEditMode.value = true
  currentRole.value = { ...row }
  roleDrawerVisible.value = true
}

const handleAssignPermissions = (row) => {
  currentRole.value = { ...row }
  permissionDrawerVisible.value = true
}

const handleAssignUsers = (row) => {
  currentRole.value = { ...row }
  userDrawerVisible.value = true
}

const handleDeleteRole = (row) => {
  ElMessageBox.confirm(
    `确定要删除角色 ${row.name} 吗？删除后该角色下的用户将失去相应权限。`,
    '删除确认',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'error',
    }
  ).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      pagination.value.total = tableData.value.length
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const handleRefresh = () => {
  loadData()
}

const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.value.current = val
  loadData()
}

// 处理角色表单提交
const handleRoleFormSubmit = (formData) => {
  if (isEditMode.value) {
    // 编辑模式：更新现有数据
    const index = tableData.value.findIndex(item => item.id === formData.id)
    if (index > -1) {
      tableData.value[index] = {
        ...tableData.value[index],
        ...formData
      }
    }
  } else {
    // 新增模式：添加新数据
    const newRole = {
      ...formData,
      id: Date.now(),
      permissions: [],
      userCount: 0,
      createTime: new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-')
    }

    tableData.value.unshift(newRole)
    pagination.value.total = tableData.value.length
  }
}

// 处理权限分配
const handlePermissionAssign = (assignData) => {
  const index = tableData.value.findIndex(item => item.id === assignData.roleId)
  if (index > -1) {
    tableData.value[index].permissions = assignData.permissions
    ElMessage.success('权限配置成功')
  }
}

// 处理用户分配
const handleUserAssign = (assignData) => {
  const index = tableData.value.findIndex(item => item.id === assignData.roleId)
  if (index > -1) {
    tableData.value[index].userCount = assignData.userIds.length
    ElMessage.success('用户分配成功')
  }
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
.role-management {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.page-header {
  padding: 24px;
  border-bottom: 1px solid #f0f0f0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;

  .page-title {
    font-size: 24px;
    font-weight: 600;
    margin: 0 0 8px 0;
  }

  .page-description {
    color: rgba(255, 255, 255, 0.8);
    margin: 0;
    font-size: 14px;
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;

  .action-left {
    display: flex;
    gap: 12px;
  }
}

.table-container {
  padding: 24px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 16px;
}

:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .el-table__header {
    background: #f8f9fa;
  }

  .el-table__row:hover {
    background: #f5f7fa;
  }
}

:deep(.el-pagination) {
  .el-pagination__total {
    color: #606266;
  }
}
</style>
